
const { testMobile } = require('../../utils/util.js');
const { schoolList, spList, courseList, projectList, gbook } = require('../../config/api/index.js')
const { setStorageSync, getStorageSync, removeStorage, clearStorageSync } = require('../../utils/wcache.js')
const app = getApp()
let self
Page({

  /**
   * 页面的初始数据
   */
	data: {
		isloading: true,
		currPage: 1,  // 当前页
		perPage: 10,  // 每页的数量
		projectLists: [{ id: -2, name: '请选择科目', pid: '', level: '' }],  // 科目列表
		schoollists: [{ id: -2, name: '请选择机构', pid: '', level: '' }],  // 机构列表
		other: [{ id: -1, name: '其他', pid: '', level: '' }],  // 其他
		pageType: '',  // 页面属性 
		indexMajor: 0,  // 当前科目下标
		indexSchool: 0,  // 当前机构下标
		inputMajor: '',  // 报名科目
		inputSchool: '',  // 报名机构
		inputSp: '',  // 活动名称
		promotionId: '',  // 活动id
		promotionType: '',  // 活动类型
		commentValue: '',  // 报名疑问
		submitStast: false,  // 提交状态判断
		inputName: '请输入学生姓名',  // 报名姓名
		inputPhone: '请输入联系电话',  // 报名电话
		pageTitle: '有问必答',
		placeholder: '请详细描述您存在的疑问',
		courseLists: [],  // 课程列表
		rulesName: '',  // 课程跳转课程名称
		schoolName: '',  // 机构名称
		dTime: 3600,  // 本地存储有效时间3600s
	},

  /**
   * 生命周期函数--监听页面加载
   */
	onLoad: function (options) {
		self = this
		self.setData({
			pageType: options.type,
			pageTitle: options.title || '有问必答',
		})
		
		wx.setNavigationBarTitle({
			title: self.formatTitle(options.title),
		})
		if (options.type == 'course'){
			courseList({
				data: {
					category: 1,
					id: options.id,
				},
				success(res) {
					self.setData({
						courseLists: res.data,
						inputSchool: res.data.school_id,
						rulesName: res.data.name,
						inputMajor: res.data.project_id,
					})	
				},
				complete(res) {
					self.setData({
						isloading: false,
					})
				}
			})
		}
		if (options.type == 'school'){
			self.getProjectList()
			schoolList({
				data:{
					category: 1,
					id: options.id,
				},
				success(res) {
					self.setData({
						schoolName: res.data.name,
						inputSchool: res.data.id,
					})
				}
			})
		}
		if (options.type == 'sp'){
			spList({
				data: {
					category: 1,
					id: options.id,
				},
				success(res) {
					self.setData({
						schoolName: res.data.school_name,
						inputSchool: res.data.school_id,
						promotionId: res.data.id,
						promotionType: res.data.type == 0 ? '优惠' : res.data.type == 1 ? '体验课' : res.data.type == 1 ? '试听课' : '讲座',
						inputSp: res.data.title
					})
				}
			})
		}
		if (options.type == 'faq'){
			let deadtime = wx.getStorageSync('ky_porject_faq_deadtime')  // 获取本地存储时间
			if (deadtime) {
				if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {  // 本地存储失效
					self.getProjectList()
					self.getSchoolList()
					removeStorage('ky_porject_faq')
					removeStorage('ky_school_faq')
				} else {
						self.setData({
						projectLists: getStorageSync('ky_porject_faq'),
						schoollists: getStorageSync('ky_school_faq'),
					})
				}
			} else {
				self.getProjectList()
				self.getSchoolList()
			}
		}
		
	},
	onShow: function () {

	},
	formatTitle(title) {  //针对复杂标题进行友好格式处理
		var title = title ? title.split('-') : ['有问必答'];
		
		return title[1] ? title[1] : title[0];
	},
	getProjectList(params) {
		const { currPage, projectLists, dTime } = self.data
		return projectList({
			data: {
				...{ category: 1, per_page: 100 },
				...params
			},
			success(res) {
				let totalPages = res.data.total_pages;
				let total_items = res.data.total_items
				if (currPage <= totalPages && (parseInt(projectLists.length) + parseInt(res.data.items.length)) < total_items) {
					self.setData({
						currPage: currPage + 1,
						projectLists: [...projectLists, ...res.data.items]
					})
					setTimeout(function () {
						self.getProjectList({ page: currPage + 1 })
					}, 0)
				} else {
					let lists = [];
					let pro = [...projectLists, ...res.data.items]
					pro.forEach((item) => {
						if (item.pid == '379' || item.pid == '380' || item.id == -2) {
							lists.push(item)
						}
					})
					setStorageSync('ky_porject_faq', lists, dTime)  // 保存本地科目列表
					self.setData({
						projectLists: lists,
						currPage: 1,
					})
				}
			},
			complete(res) {
				self.setData({
					isloading: false,
					
				})
			}
		})
	},
	getSchoolList(params) {  // 获取全部机构
		const { currPage, schoollists, other, dTime } = self.data
		return schoolList({
			data: {
				...{ category: 1 },
				...params
			},
			success(res) {
				let totalPages = res.data.total_pages
				let total_items = res.data.total_items
				if (currPage <= totalPages && (parseInt(schoollists.length) + parseInt(res.data.items.length)) < total_items) {
					self.setData({
						currPage: currPage + 1,
						schoollists: [...schoollists, ...res.data.items]
					})
					setTimeout(function () {
						self.getSchoolList({ page: currPage + 1 })
					}, 0)
				} else {
					let lists = [...schoollists, ...res.data.items, ...other]
					
				  setStorageSync('ky_school_faq', lists, dTime)  // 保存本地机构列表
					self.setData({
						schoollists: lists,
						currPage: 1,
					})
				}
			},
			complete(res) {
				self.setData({
					isloading: false
				})
			}
		})
	},
	commentBind: function (e) {
		this.setData({
			commentValue: e.detail.value
		})
	},
	onSubmit: function () {
		const { inputName, inputPhone, inputMajor, inputSchool, rulesName, commentValue, submitStast, pageType, schoollists, indexSchool, projectLists, indexMajor, pageTitle, courseLists, schoolName, promotionType, promotionId, inputSp } = self.data
		if (!submitStast && inputName == '请输入学生姓名') {
			wx.showToast({
				title: '姓名不能为空',
				image: '/assert/imgs/error_tip.png',
			})
			return false;
		}
		if (!testMobile(inputPhone)) {
			wx.showToast({
				title: '手机号码错误',
				image: '/assert/imgs/error_tip.png',
			})
			return false;
		}
		if ((!inputMajor || inputMajor == -2) && pageType != 'sp') {
			wx.showToast({
				title: '科目不能为空',
				image: '/assert/imgs/error_tip.png',
			})
			return false;
		}
		if (!inputSchool || inputSchool == -2) {
			wx.showToast({
				title: '机构不能为空',
				image: '/assert/imgs/error_tip.png',
			})
			return false;
		}
		if (!submitStast) {
			wx.showToast({
				title: '隐私保障为勾选',
				image: '/assert/imgs/error_tip.png',
			})
			return false;
		}
		let school_name = courseLists.school_name || schoolName || schoollists[indexSchool]['name']
		let major_name = inputSp || projectLists[indexMajor]['name'] 
		let formInfo = {
			"category":1,
			"project": parseInt(inputMajor) || '',
			"promotion": parseInt(promotionId) || '',
			"school": parseInt(inputSchool) || '',
			"custom": inputName || '',
			"phone": inputPhone || '',
			"mark": commentValue || '',
			"content": (rulesName ? school_name + '-' + rulesName + '-考研小程序' : school_name + '-' + major_name + '-考研小程序') + '-' + pageTitle,
			subsite_id: 53
		}
		for (var key in formInfo) {
			if (formInfo[key] === '') {
				delete formInfo[key]
			}
		}
		gbook({
			data: formInfo,
			success(res) {
				if (res.errCode == 200) {
					wx.showToast({
						title: '提交成功',
						image: '/assert/imgs/success_tip.png',
						duration: 2000,
					})
					self.setData({
						indexMajor: 0,
						inputMajor: ''
					})
				} else {
					wx.showToast({
						title: '提交失败',
						image: '/assert/imgs/error_tip.png',
						duration: 2000,
					})
				}
			}
		})
	},
	checkboxChange: function (e) {
		self.setData({
			submitStast: e.detail.value == "1" ? true : false,
		})
	},
	inputName: function (e) {
		self.setData({
			inputName: e.detail.value
		})
	},
	inputNameBlur: function (e) {
		self.setData({
			inputName: e.detail.value || '请输入学生姓名',
			submitStast: e.detail.value ? true : false
		})
	},
	inputPhoneBlur: function (e) {
		self.setData({
			inputPhone: e.detail.value || '请输入联系电话',
			submitStast: e.detail.value ? true : false
		})
	},
	inputPhone: function (e) {
		self.setData({
			inputPhone: e.detail.value
		})
	},
	inputMajor: function (e) {
		self.setData({
			inputMajor: e.detail.value
		})

	},
	majorChange: function (e) {
		this.setData({
			indexMajor: e.detail.value,
			inputMajor: self.data.projectLists[e.detail.value].id
		})
	},
	schoolChange: function (e) {
		self.setData({
			indexSchool: e.detail.value,
			inputSchool: self.data.schoollists[e.detail.value].id
		})
	},
	inputSchool: function (e) {
		self.setData({
			inputSchool: e.detail.value
		})
	},
	guaranteePage: function () {
		wx.navigateTo({
			url: '/pages/guarantee/guarantee',
		})
	},

  /**
   * 用户点击右上角分享
   */
	onShareAppMessage: function () {
		return {
			title: '考研' + self.data.pageTitle,
			path: '/pages/form-page/form-page'
		}
	}
})